<template>
  <div class="environmentManagement-detail">
    <NavTitle :title="navTitle" />
    <div class="environmentManagement-detail-content">
      <div class="environmentManagement-detail-content-table">
        <Table
          ref="tableRef"
          :columns="columns"
          :data="loadData"
          :alert="false"
          bordered
          :row-key="(record: any) => record.id"
        >
          <template #operator>
            <a-space>
              <a-button
                type="primary"
                @click="add('add')"
                v-auth="{ objectId: appData.code, objectType: ResourceType.app, role: Role.manager }"
              >
                <PlusOutlined />
                添加环境
              </a-button>
            </a-space>
          </template>
          <template>
            <a-avatar style="width: 25px; height: 25px" />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'action'">
              <div class="table-operation">
                <a @click="handelDetial(record)">详情</a>
                <a
                  @click="handelAction('edit', record)"
                  v-auth="{ objectId: appData.code, objectType: ResourceType.app, role: Role.manager }"
                  >编辑</a
                >
                <a
                  @click="handelDelete(record)"
                  v-auth="{ objectId: appData.code, objectType: ResourceType.app, role: Role.manager }"
                  >删除</a
                >
              </div>
            </template>
          </template>
        </Table>
      </div>
    </div>
  </div>

  <BasicModal
    ref="addEnvironmentModal"
    :title="`${modalType}环境`"
    width="400px"
    :confirmLoading="editEnvironmentLoading"
    @emit-callback-fn="addCallbackFn($event)"
  >
    <template #content>
      <AddEnviromentForm ref="formRef" />
    </template>
  </BasicModal>
</template>

<script setup lang="ts">
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
import {
  querEnvironmentPageListFun,
  addEnvironmentFun,
  querSpaceFun,
  deleteEnvironmentFun,
  putEnvironmentFun,
  checkIsEnvironmentPipeline,
} from '@/api/applicationManagement';

import { message } from 'ant-design-vue';
import { validatorCode } from '@/settings/commonSettings';
import { useApplicationStore } from '@/store/modules/app';
import { storeToRefs } from 'pinia';
import { ResourceType, Role } from '@/enums/pipelineEnum';
import { formatToDatetime } from '@/utils/DateUtil';
const counterStore = useApplicationStore();
const { appData } = storeToRefs(counterStore);

const navTitle = ref('环境管理');
const columns = [
  { dataIndex: 'code', title: '环境编码', align: 'center' },
  { dataIndex: 'name', title: '环境名称', align: 'center' },
  { dataIndex: 'spaceName', title: '交付空间', align: 'center' },
  { dataIndex: 'description', title: '描述', align: 'center', width: 300, ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 220,
  },
];
const editEnvironmentLoading = ref<boolean>(false);
const tableRef = ref<any>('');

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      applicationCode: appData.value.code,
    },
  };
  const data = await getList(parameObj);
  return data;
};

//获取表格数据
const getList = async (parameObj: any) => {
  return await querEnvironmentPageListFun(parameObj).then((res: any) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res.records,
    };
    return data;
  });
};
const emits = defineEmits(['updateLoading']);
const modalType = ref('添加');
const addEnvironmentModal = ref<any>(null);
const selectSpaceOptions = ref([]);

enum ModalType {
  ADD = '添加',
  EDIT = '编辑',
}

const editSchemas = [
  {
    field: 'code',
    label: '环境编码',
    labelWidth: 80,
    colProps: {
      span: 24,
    },
    rules: [
      {
        required: true,
        validator: (_, value: any) => {
          return new Promise((resolve, reject) => {
            if (!value) {
              reject(new Error('环境编码不能为空'));
            } else if (!validatorCode.test(value)) {
              reject(new Error('请输入长度不超过50字符的小写字母、数字或中划线，且不能以中划线开头或结尾。'));
            } else {
              resolve();
            }
          });
        },
      },
    ],
    component: 'Input',
  },
  {
    field: 'name',
    label: '环境名称',
    labelWidth: 80,
    required: true,
    colProps: {
      span: 24,
    },
    component: 'Input',
  },
  {
    field: 'spaceUuid',
    label: '交付空间',
    labelWidth: 80,
    required: true,
    colProps: {
      span: 24,
    },
    componentProps: {
      options: selectSpaceOptions,
    },
    component: 'Select',
  },
  {
    field: 'description',
    label: '应用描述',
    labelWidth: 80,
    required: false,
    colProps: {
      span: 24,
    },
    component: 'InputTextArea',
  },
] as FormSchema[];

const detailExtendSchemas = [
  {
    field: 'updater',
    label: '变更人',
    labelWidth: 80,
    required: true,
    colProps: {
      span: 24,
    },
    component: 'Input',
  },
  {
    field: 'updateTime',
    label: '变更时间',
    labelWidth: 80,
    required: true,
    colProps: {
      span: 24,
    },
    component: 'Input',
  },
] as FormSchema[];

//新增||编辑应用form
const [AddEnviromentForm, formRef] = useForm({
  schemas: editSchemas,
});

//获取交付空间
const getSpaceList = async () => {
  await querSpaceFun({}).then((res: any) => {
    const options = res.map((item: any) => {
      return {
        label: item.name,
        value: item.uuid,
      };
    });
    selectSpaceOptions.value = options;
  });
  emits('updateLoading', false);
};

onMounted(() => {
  getSpaceList();
});

//打开添加环境弹窗
const add = (type: string) => {
  modalType.value = type == 'add' ? ModalType.ADD : ModalType.EDIT;
  addEnvironmentModal.value.showModal();
};

const addCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  let parameObj: any = {
    ...data,
    applicationCode: appData.value.code,
  };
  editEnvironmentLoading.value = true;
  if (modalType.value == ModalType.ADD) {
    await addEnvironmentFun(parameObj)
      .then(() => {
        message.success('添加成功');
        tableRef.value.refresh(true);
        addEnvironmentModal.value.hideModal();
      })
      .finally(() => {
        editEnvironmentLoading.value = false;
      });
  }

  if (modalType.value == ModalType.EDIT) {
    parameObj = {
      ...parameObj,
      uuid: obj.propsData.uuid,
    };
    await putEnvironmentFun(parameObj)
      .then(() => {
        message.success('编辑成功');
        tableRef.value.refresh(true);
        addEnvironmentModal.value.hideModal();
      })
      .finally(() => {
        editEnvironmentLoading.value = false;
      });
  }
};

//表格详情
const handelDetial = (record: any) => {
  nextTick(() => {
    formRef.resetSchema([...editSchemas, ...detailExtendSchemas] as any);
    formRef.setFieldsValue({ ...record, updateTime: formatToDatetime(record.updateTime) });
    formRef.setSchemaFormProps({ disabled: true });
  });
  addEnvironmentModal.value.showModal(record, '关闭');
};

//表格编辑
const handelAction = (type: string, record: any) => {
  modalType.value = type == 'add' ? ModalType.ADD : ModalType.EDIT;
  if (type === 'edit') {
    nextTick(() => {
      formRef.setFieldsValue(record);
      formRef.updateSchema({
        field: 'code',
        label: '环境编码',
        labelWidth: 80,
        required: true,
        componentProps: { disabled: true },
        colProps: {
          span: 24,
        },
        component: 'Input',
      });
    });
  }

  addEnvironmentModal.value.showModal(record);
};

//表格删除
const handelDelete = (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode(
      'div',
      { style: 'color:black;' },
      `确定要删除“环境编码：${record.code}，环境名称：${record.name}”这一项数据吗？`,
    ),
    async onOk() {
      await checkIsEnvironmentPipeline(record.uuid).then(async (res: any) => {
        if (res) {
          Modal.confirm({
            title: '提示',
            icon: createVNode(ExclamationCircleOutlined),
            centered: true,
            maskClosable: false,
            keyboard: false,
            content: createVNode('div', {}, '该环境下已绑定流水线，不允许删除!'),
            okText: '关闭',
            cancelText: ' ',
          });
          return false;
        }
        await deleteEnvironmentFun(record.uuid).then(() => {
          message.success('删除成功');
          tableRef.value.refresh(true);
        });
      });
    },
    onCancel() {},
    class: 'test',
  });
};
</script>

<style lang="less" scoped>
.environmentManagement-detail {
  &-content {
    &-table {
      margin-top: 16px;
    }
  }
}
</style>
